package com.zhiletu.collect.control;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;

import javax.servlet.http.HttpServlet;

import com.zhiletu.collect.Collecter;
import com.zhiletu.collect.config.CollectConfig;
import com.zhiletu.collect.util.DateUtil;
import com.zhiletu.collect.util.ParseString;
import org.apache.log4j.Logger;

import static java.util.concurrent.TimeUnit.SECONDS;

/**
 *
 * @Title: UdastConfigServlet.java
 * @Package com.zhiletu.collect.control
 * @Description: 采集定时任务入口控制
 * @author zhiletu.com
 * @date 2021年3月11日
 * @version V1.0
 */
public class UdastConfigServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	private static final ScheduledExecutorService sheduExec = Executors
			.newScheduledThreadPool(1);

	private static Logger log = Logger.getLogger(UdastConfigServlet.class);

	private static boolean initFlag = true;

	public UdastConfigServlet() {
	}

	public void init() {
		initUdast();
	}

	private void initUdast() {
		if (!"true".equalsIgnoreCase(CollectConfig
				.getProperty("TASK_APPLY_ACTIVE"))) {
			sheduExec.shutdown();
		}
		else {
			String initDelay = ParseString.nvl(CollectConfig
					.getProperty("INITIAL_DELAY"));
			final long initialDelay = Long
					.parseLong("".equals(initDelay) ? "30" : initDelay); // default
			// 30s

			String startdelay = ParseString.nvl(CollectConfig
					.getProperty("DELAY_BETWEEN_THREAD"));
			final long delay = Long.parseLong("".equals(startdelay) ? "30"
					: startdelay); // default 30s 
			String sethour = ParseString.nvl(CollectConfig
					.getProperty("EXEC_HOUR")); // 整点执行设置
			final int hour = Integer.parseInt("".equals(sethour) ? "6"
					: sethour);// 默认早晨6点整

			final String always = ParseString.nvl(CollectConfig
					.getProperty("EXEC_ALWAYS")); // 轮询执行
			// 定时任务
			final Runnable taskApply = new Runnable() {
				@Override
				public void run() {
					try {
						boolean token = false;
						if (initFlag) {
							token = true;
							initFlag = false;
						}
						else {
							int exec = DateUtil.getTimeToSet(hour);
							if ("true".equalsIgnoreCase(always)) {
								token = true;
							}
							else if (exec <= delay) {
								token = true;
							}
							else {
								log.info("将在以下时间执行，整点：" + hour + " 请设置执行周期为1小时");
								return;
							}
						}

						if (token) {
							log.info("开始执行任务……");
							Collecter.execRule();
							log.info("执行任务成功……");
						}
					}
					catch (Throwable e) {
						log.error(e);
					}
					finally {
						//System.gc();
						log.info("回收资源成功……");
					}
				}
			};

			final ScheduledFuture<?> taskHandle = sheduExec
					.scheduleWithFixedDelay(taskApply, initialDelay, delay,
							SECONDS);

			if (!taskHandle.isCancelled()) {
				log.info("^采集任务处理执行中……");
			}
		}
	}
}
